package linklist;

/*给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。*/
public class ReverseList {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseList(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode newHead = new ListNode();
        ListNode tmpNode;
        //头插法逆置链表
        while(head != null){
            //保存下一次头节点防止断链
            tmpNode = head.next;
            head.next = newHead.next;
            newHead.next = head;
            head = tmpNode;
        }
        return newHead.next;
    }
}
